import asyncio
import os, sys
import logging
from typing import Any, Dict, List, Optional, Union, AsyncGenerator

#import pandas as pd
# in jupyter notebook current_path get with dir '.'
# current_path = os.path.abspath('.')
current_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(current_path+'/..')
import json
from core.providers import OllamaProvider
from core.weather import MCPClient, SimpleMCPClient

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s')
logger = logging.getLogger(__name__)

DEFAULT_API_HOST = "http://localhost:11434"
async def load_mcp_config_from_file(config_path="mcp_config.json") -> dict:
    """
    Load MCP configuration from a JSON file.
    
    Args:
        config_path: Path to the configuration file
        
    Returns:
        Dict containing the configuration
        
    Raises:
        SystemExit: If the file is not found or contains invalid JSON
    """
    try:
        with open(config_path, "r") as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"Error: {config_path} not found.")
        sys.exit(1)
    except json.JSONDecodeError:
        print(f"Error: Invalid JSON in {config_path}.")
        sys.exit(1)

async def log_messages_to_file(messages: List[Dict], functions: List[Dict], log_path: str):
    """
    Log messages and function definitions to a JSONL file.

    Args:
        messages: List of messages to log
        functions: List of function definitions
        log_path: Path to the log file
    """
    try:
        # Create directory if it doesn't exist
        log_dir = os.path.dirname(log_path)
        if log_dir and not os.path.exists(log_dir):
            os.makedirs(log_dir)

        # Append to file
        with open(log_path, "a") as f:
            f.write(json.dumps({
                "messages": messages,
                "functions": functions
            }) + "\n")
    except Exception as e:
        logger.error(f"Error logging messages to {log_path}: {str(e)}")

async def main():
    logger.info("Start weather test client")
    if len(sys.argv) < 2:
        print("Usage: python client.py <path_to_server_script>")
        sys.exit(1)
    server_name="weather"
    model_name="qwen3:0.6b"
    # 1) Load config from file:
    config = await load_mcp_config_from_file(current_path+"/config.json")
    models_cfg = config.get("models", [])
    # 2) Choose Model
    chosen_model = None
    if model_name:
        for m in models_cfg:
            if m.get("model") == model_name or m.get("title") == model_name:
                chosen_model = m
                break
        if not chosen_model:
            # fallback to default or fail
            for m in models_cfg:
                if m.get("default"):
                    chosen_model = m
                    break
    else:
        # if model_name not specified, pick default
        for m in models_cfg:
            if m.get("default"):
                chosen_model = m
                break
        if not chosen_model and models_cfg:
            chosen_model = models_cfg[0]
    logger.info(f"Server {server_name}: chosen model {chosen_model}")
    # 3) Start server(single server)
    server_script_path=sys.argv[1]
    client = SimpleMCPClient(
                server_name=server_name,
                command="python",
                models_cfg=chosen_model,
                args=[server_script_path],
                env=None )
    try:
        await client.start()
        await client.create_model("ollama")
        await client.chat_loop()
    finally:
        await client.cleanup()

if __name__ == "__main__":
    import sys
    """
    g=globals()
    print(type(g),f"{g}")
    for x in list(g.keys()):
        if x=="g":
            continue
        print(x,g[x])
    sys.exit()
    """
    asyncio.run(main())